package com.codeoss.framework.util;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.parser.DataParseContext;
import com.codeoss.framework.data.parser.IDataParseContext;
import com.codeoss.framework.data.parser.ITableParser;
import com.codeoss.module.ir.model.IrModel;
import com.codeoss.module.ir.service.IIrModelService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class TableBuilder {
	public static Table build(String tableName,  ObjectMapper objectMapper,ITableParser tableParser, IIrModelService irModelService) {
		QueryWrapper<IrModel> irModelQuery = new QueryWrapper<IrModel>();
		irModelQuery.eq("table_name", tableName);
		IrModel irModel = irModelService.getOne(irModelQuery);
		String jsonContent = irModel.getJsonContent();
		ObjectNode modelNode;
		try {
			modelNode = (ObjectNode) objectMapper.readTree(jsonContent);
			IDataParseContext dataParseContext = new DataParseContext();
			Table dataTable = tableParser.parser(dataParseContext, modelNode);
			Table tempTable=dataTable;
			List<Column> allColumnList = new ArrayList<Column>();
			allColumnList.addAll(dataTable.getColumnList());
			String superTable = dataTable.getExtendsTable();
			while (!StringUtils.isEmpty(superTable)) {
				irModelQuery=new QueryWrapper<IrModel>();
				irModelQuery.eq("table_name", superTable);
				irModel = irModelService.getOne(irModelQuery);
				jsonContent = irModel.getJsonContent();
				modelNode=(ObjectNode) objectMapper.readTree(jsonContent);
				dataParseContext = new DataParseContext();
				dataTable = tableParser.parser(dataParseContext, modelNode);
				if(tempTable.getSuperTable()==null) {
					tempTable.setSuperTable(dataTable);
				}
				allColumnList.addAll(dataTable.getColumnList());
				superTable = dataTable.getExtendsTable();
			}
			tempTable.setAllColumnList(allColumnList);
			tempTable.build();
			return tempTable;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
